package com.interest.plus2.net;


import com.interest.plus2.bean.BaseBean;
import ohos.app.Context;
import retrofit2.Call;
import retrofit2.Response;

import java.lang.reflect.ParameterizedType;


/**
 * 泛型方式
 *
 * @param <T>
 */
public abstract class NetGenericityObserver<T> extends RxNetObserver<T> implements NetCallBack<BaseBean<T>> {

    public NetGenericityObserver(Context context) {
        super(context);
    }

    @Override
    public void onSubscribe(Call<BaseBean<T>> call) {
        try {
            onSubscribed(call);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Call<BaseBean<T>> call, Throwable throwable) {

    }

    @Override
    public void onResponse(Call<BaseBean<T>> call, Response<BaseBean<T>> response) {
        BaseBean<T> info = response.body();
        if (info == null) {
            try {
                onFail("onNext method parameter is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        if (info.getCode() == RESPONSE_CODE_OK) {
            try {
                if (info.getResult() != null) {
                    onSuccess(info.getResult(), info.getMessage());
                } else if (info.getResult() != null) {
                    onSuccess(info.getResult(), info.getMessage());
                } else {
                    try {
                        ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
                        Class clazz = (Class<T>) ptype.getActualTypeArguments()[0];
                        T o = (T) clazz.newInstance();
                        onSuccess(o, "暂无数据");
                    } catch (Exception e) {
                        onSuccess(null, "解析错误");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //对服务器返回的通用问题的统一拦截处理
            if (con != null && con.get() != null) {
                try {
//                    DeviceInfo.analysisCode(con.get(), info.getCode(), info.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                onFail(info.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
